<template>
    <div class="layout">
        <div class="container">
            <ZWGroup
                ref="GroupingRef"
                :type="29"
                :group-id="group_id"
                :auth-code="authCode"
                @submit="handleGroupSubmit" />
            <div class="container_right">
                <ZwSearchForm row-num="3" :option="searchOption" @search="search" @reset="reset" />
                <ZwTable
                    ref="tableRef"
                    class="table-box"
                    tab-h="initial"
                    :option="tableOption"
                    :fetch-params="state.searchParams"
                    :row-key="getRowKey"
                    :fetch-api="fetchApi()"
                    :close-loading="true"
                    @select="onSelect"
                    @selection-change="onSelectionChange"
                    @select-all="onSelectAll">
                    <template #headerOperate>
                        <el-dropdown class="dropdown_btn">
                            <el-button plain :disabled="!checkList.length">
                                批量操作
                                <el-icon class="el-icon--right"><arrow-down /> </el-icon>
                            </el-button>
                            <template #dropdown>
                                <el-dropdown-menu>
                                    <el-dropdown-item v-auth="'BATCH_BEGAN_LBSPULLGROUP'" @click="onChange(1)">
                                        批量开始
                                    </el-dropdown-item>
                                    <el-dropdown-item v-auth="'BATCH_OVER_LBSPULLGROUP'" @click="onChange(2)">
                                        批量结束
                                    </el-dropdown-item>
                                    <el-dropdown-item v-auth="'BATCH_DOWNLOAD_LBSPULLGROUP'" @click="onChange(3)">
                                        批量下载
                                    </el-dropdown-item>
                                    <!-- <el-dropdown-item v-auth="'BATCH_DEL_LBSPULLGROUP'" @click="onChange(4)"> 批量删除</el-dropdown-item> -->
                                </el-dropdown-menu>
                            </template>
                        </el-dropdown>
                        <el-button v-auth="'ADD_LBSPULLGROUP'" type="primary" @click="toCreateActivity">
                            新建活动
                        </el-button>
                    </template>
                </ZwTable>
            </div>
        </div>
    </div>
    <!-- 删除弹框 -->
    <ZWDeletdialog ref="DeletdialogRef" @submit="onSubmit" />
</template>

<script lang="tsx">
import { defineComponent } from 'vue';
// 定义name专用script标签
// eslint-disable-next-line vue/component-definition-name-casing
export default defineComponent({ name: 'LBS_PULL_GROUP' });
</script>

<script setup lang="tsx">
import ZwSearchForm from '@/components/zw/search-form/SearchForm';
import ZwTable from '@/components/zw/table/Table';
import ZWDeletdialog from '@/components/ZWDeletdialog.vue';
import ZWGroup from '@/components/ZWGroup.vue';
import { getGroupList } from '@/api/concreation';
import useClipboard from 'vue-clipboard3';
import { ElMessage, ElImage, ElIcon, ElButton } from 'element-plus';
import { Picture as IconPicture } from '@element-plus/icons-vue';
import { funAllList, delList, changeList, downloadList } from '@/api/customer/groupManage/lbspullgroup';
import { ref, reactive, computed, onActivated, onMounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { deepCopy } from '@/utils/helper';
import { StatusColor, DOWLOAD_FILE } from '@/utils/smartMarketing';
import { useStore } from '@/store';
import { getCreateList } from '@/api/common';
import { endLoading, startLoading } from '@/utils/request';
import { isCachePage } from '@/utils/utils';

const store = useStore();
const DeletdialogRef: any = ref(null);
const router = useRouter();
const route = useRoute();
const GroupingRef: any = ref(null);
const isShow = ref(0);
const checkList = ref([]);
const delId = ref<any>([]);
const targetArr = reactive<Array<any>>([]);
const group_id = ref<number | string>('all');

const requestFlag = ref<boolean>(false);
const currentParams = ref<any>(null);

const tableRef = ref<HTMLElement | null>(null);

const defaultParams = {
    group_id: 'all',
    name: '', //活动标题
    work_user_id: '', //创建人id
    activity_status: 0, //活动状态 0-全部 1-未开始 2-进行中 3-已结束 4-提前结束
    activity_time: [] //创建时间
};

const state = reactive({
    searchParams: deepCopy(defaultParams)
});

// 分组权限code码
const authCode = {
    add: 'ADD_CHILD_LBS',
    edit: 'EDIT_CHILD_LBS',
    del: 'DEL_CHILD_LBS'
};
const handleGroupSubmit = (v: any) => {
    // 解决切换分组，点击新增然后取消之后的默认分组问题 ⬇️
    router.push({ path: '/customer/groupManage/lbspullgroup', query: { group_id: v.id } });
    group_id.value = v.id;
    currentParams.value = { ...deepCopy(defaultParams), ...currentParams.value, group_id: group_id.value };
    state.searchParams = deepCopy(currentParams.value);
    tableRef.value?.clearSelection();
};

// 复制
const { toClipboard } = useClipboard();
const onCopy = async (v: any) => {
    try {
        await toClipboard(v);
        ElMessage.success('复制成功');
    } catch (e) {
        ElMessage.error('复制失败');
    }
};

const searchOption = computed(() => {
    return [
        {
            label: '活动搜索',
            name: 'name',
            value: '',
            type: 'input',
            placeholder: '请输入活动标题/描述'
        },
        {
            label: '创建人',
            name: 'work_user_id',
            value: [],
            multiple: true,
            type: 'select',
            filterable: true,
            placeholder: '请选择创建人',
            fetchOptionApi: () => {
                return new Promise(resolve => {
                    getCreateList({}).then((res: any) => {
                        const targetArr = res.map((item: any) => {
                            item.name = `${item.name}  (${item.phone}) `;
                            return item;
                        });
                        resolve(targetArr);
                    });
                });
            },
            formatOption: (v: any) => ({
                label: v.name,
                value: v.id
            })
        },
        {
            label: '活动有效期',
            name: 'activity_time',
            value: [],
            type: 'datePicker',
            datePickerType: 'daterange',
            datePickerFormat: 'YYYY-MM-DD HH:mm:ss',
            valueFormat: 'YYYY-MM-DD HH:mm:ss',
            startPlaceholder: '开始日期',
            endPlaceholder: '结束日期'
        },
        {
            label: '活动状态',
            name: 'activity_status',
            type: 'select',
            clearable: false,
            placeholder: '请选择',
            optionList: [
                { name: '全部', id: 0 },
                { name: '未开始', id: 1 },
                { name: '进行中', id: 2 },
                { name: '已结束', id: 3 },
                { name: '提前结束', id: 4 }
            ],
            formatOption: (v: any) => ({
                label: v.name,
                value: v.id
            })
        }
    ];
});

const search = (v: any) => {
    tableRef.value?.clearSelection();
    currentParams.value = { ...deepCopy(defaultParams), ...v, group_id: group_id.value };
    state.searchParams = deepCopy(currentParams.value);
};
const reset = (v: any) => {
    tableRef.value?.clearSelection();
    currentParams.value = { ...deepCopy(defaultParams), group_id: group_id.value };
    state.searchParams = deepCopy(currentParams.value);
};

// 表格
const tableOption = [
    {
        type: 'selection',
        width: 55,
        fixed: 'left',
        reserveSelection: true
    },
    {
        prop: 'activity_name',
        label: '标题',
        minWidth: 130
    },
    {
        prop: 'qr_code_link',
        label: '二维码',
        align: 'center',
        width: 100,
        render({ row, column, index }) {
            const slotError = () => (
                <div class="image-slot">
                    <ElIcon>
                        <IconPicture />
                    </ElIcon>
                </div>
            );
            return (
                <>
                    <ElImage
                        preview-src-list={[row.qr_code_link]}
                        preview-teleported={true}
                        src={row.qr_code_link}
                        style="width: 48px; height: 48px; font-size: 49px"
                        vSlots={{ error: slotError }}
                    />
                </>
            );
        }
    },
    {
        prop: 'region_num',
        label: '区域数',
        align: 'center',
        width: 80,
        render({ row, column, index }) {
            return row.region_num || '0';
        }
    },
    {
        prop: 'groupchat_num',
        label: '企微外部群数',
        align: 'center',
        width: 120,
        render({ row, column, index }) {
            return row.groupchat_num || '0';
        }
    },
    {
        prop: 'contact_num',
        label: '净增人数',
        align: 'center',
        width: 100,
        render({ row, column, index }) {
            return row.contact_num || '0';
        }
    },
    {
        prop: 'touch_num',
        label: '可触达好友数',
        align: 'center',
        width: 120
    },
    {
        prop: 'group_name',
        label: '所属分组',
        align: 'center',
        width: 150
    },
    {
        prop: 'created_user',
        label: '创建人',
        width: 150
    },
    {
        prop: 'activity_time',
        label: '活动有效期',
        width: 336,
        render({ row, column, index }) {
            return (
                <>
                    {row.period_type == 1 ? (
                        '永久'
                    ) : (
                        <div>
                            {row.begin_date} - {row.end_date}
                        </div>
                    )}
                </>
            );
        }
    },
    {
        prop: 'status_name',
        label: '状态',
        minWidth: 100,
        align: 'center',
        render({ row, column, index }) {
            const status = {
                1: '未开始',
                2: '进行中',
                3: '已结束',
                4: '提前结束'
            };
            return (
                <span style={StatusColor(status[row.activity_status], 'obj')?.color}>
                    {StatusColor(status[row.activity_status], 'obj')?.name}
                </span>
            );
        }
    },
    {
        prop: 'operate',
        label: '操作',
        width: 295,
        fixed: 'right',
        isOperate: true,
        option: [
            // {
            //   name: '查看',
            //   authCode: 'VIEW',
            //   click: (row: any) => {
            //     router.push({
            //     path: '/customer/groupManage/lbspullgroup/create',
            //     query: { type: 'detail', id: row.id }
            //   })
            //   }
            // },
            {
                name: '编辑',
                authCode: 'EDIT',
                click: (row: any) => {
                    router.push({
                        path: '/customer/groupManage/lbspullgroup/create',
                        query: { type: 'edit', id: row.id }
                    });
                },
                isRender: ({ row }: any) => [1, 2].includes(row.activity_status)
            },
            {
                name: '立即开始',
                authCode: 'BEGIN',
                click: (row: any) => {
                    delId.value = [row.id];
                    onChange(1);
                },
                isRender: ({ row }: any) => [1].includes(row.activity_status)
            },
            {
                name: '提前结束',
                authCode: 'OVER',
                click: (row: any) => {
                    delId.value = [row.id];
                    onChange(2);
                },
                isRender: ({ row }: any) => row.activity_status === 2
            },
            {
                name: '下载',
                authCode: 'DOWNLOAD',
                click: (row: any) => {
                    delId.value = [row.id];
                    onChange(5);
                },
                isRender: ({ row }: any) => [1, 2].includes(row.activity_status)
            },
            {
                name: '复制',
                authCode: 'COPY',
                click: (row: any) => {
                    onCopy(row.activity_url);
                },
                isRender: ({ row }: any) => [1, 2].includes(row.activity_status)
            },
            {
                name: '统计',
                authCode: 'STAT',
                click: (row: any) => {
                    router.push(`/customer/groupManage/lbspullgroup/statistics?id=${row.id}`);
                },
                isRender: ({ row }: any) => row.activity_status !== 1
            },
            {
                name: '删除',
                authCode: 'DELETE',
                click: (row: any) => {
                    delId.value = [row.id];
                    onChange(4);
                },
                isRender: ({ row }: any) => row.activity_status !== 2
            }
        ]
    }
];
const getRowKey = (row: any) => {
    return row.id;
};
const fetchApi = () => {
    // 获取文件列表
    // return getFissionList
    return funAllList;
};
// 选中表格 checkbox
const onSelect = (selection, row) => {
    if (selection.constructor === Array) checkList.value = selection.map(v => v.id);
};
// 选择项变更
const onSelectionChange = selection => {};
// 全选
const onSelectAll = selection => {
    checkList.value = selection.map(v => v.id);
};
const onChange = (num: number) => {
    //1开始，2结束，3下载。4删除, 5 单个下载
    switch (num) {
        case 1:
            DeletdialogRef.value.appDialog.title = '开始提醒';
            DeletdialogRef.value.content = '确认开始当前活动吗？';
            break;
        case 2:
            DeletdialogRef.value.appDialog.title = '结束提醒';
            DeletdialogRef.value.content = '确认结束当前活动吗？';
            break;
        case 3:
            DeletdialogRef.value.appDialog.title = '下载提醒';
            DeletdialogRef.value.content = '确认下载所选活动吗？';
            break;
        case 4:
            DeletdialogRef.value.appDialog.title = '删除提醒';
            DeletdialogRef.value.content = '确认删除所选活动吗？';
            break;
        case 5:
            DeletdialogRef.value.appDialog.title = '下载提醒';
            DeletdialogRef.value.content = '确认下载所选活动吗？';
            break;
    }
    isShow.value = num;
    DeletdialogRef.value.appDialog.visible = true;
};
const onSubmit = async () => {
    startLoading();
    try {
        const params = delId.value.length ? delId.value : checkList.value;
        switch (
            isShow.value //1开始，2结束，3下载。4删除
        ) {
            case 1:
                await changeList({ ids: params, status: 1 });
                ElMessage.success('活动开始成功');
                delId.value = [];
                checkList.value = [];
                DeletdialogRef.value.appDialog.visible = false;
                tableRef.value.reload();
                tableRef.value?.clearSelection();
                break;
            case 2:
                await changeList({ ids: params, status: 2 });
                ElMessage.success('活动结束成功');
                delId.value = [];
                checkList.value = [];
                DeletdialogRef.value.appDialog.visible = false;
                tableRef.value.reload();
                tableRef.value?.clearSelection();
                break;
            case 3:
                // eslint-disable-next-line no-case-declarations
                const { url: res } = await downloadList({ id: params });
                DOWLOAD_FILE(res.url, res.name);
                ElMessage.success('活动下载成功');
                delId.value = [];
                checkList.value = [];
                DeletdialogRef.value.appDialog.visible = false;
                tableRef.value.reload();
                tableRef.value?.clearSelection();
                break;
            case 4:
                await delList({ id: params });
                ElMessage.success('删除成功');
                delId.value = [];
                checkList.value = [];
                DeletdialogRef.value.appDialog.visible = false;
                await GroupingRef.value.getGroup(29);
                tableRef.value.reload();
                tableRef.value?.clearSelection();
                break;
            case 5:
                // eslint-disable-next-line no-case-declarations
                const { url: res2 } = await downloadList({ id: params });
                DOWLOAD_FILE(res2.url, res2.name);
                ElMessage.success('活动下载成功');
                DeletdialogRef.value.appDialog.visible = false;
                break;
        }
    } catch (error) {
        endLoading();
    }
};
// 新增活动
const toCreateActivity = () => {
    router.push({ path: '/customer/groupManage/lbspullgroup/create', query: { group_id: group_id.value } });
};

onActivated(async (val: any) => {
    const groupId = Number(route.params?.group_id || route.query?.group_id);
    if (isCachePage() || groupId || groupId == 0) {
        if ((groupId || groupId == 0) && group_id.value != groupId) {
            group_id.value = groupId;
        } else {
            await GroupingRef.value.getGroup(29);
        }
        tableRef.value?.clearSelection();
        GroupingRef.value.setCurrentSelectId({ id: group_id.value });
        state.searchParams = {
            ...deepCopy(defaultParams),
            ...currentParams.value,
            group_id: groupId || group_id.value
        };
    }
});
</script>

<style lang="scss" scoped>
.layout {
    .container {
        display: flex;

        .container_right {
            height: calc(100vh - 142px);
            padding: 24px;
            border: 1px solid #eaeaea;
            border-radius: 4px;
            box-sizing: border-box;
            background-color: #fff;
            display: flex;
            flex-direction: column;
            overflow: hidden;

            .zw-table {
                display: flex;
                flex-direction: column;
                flex: 1;
                overflow: hidden;

                :deep(.el-table) {
                    flex: 1;

                    .el-table__empty-block {
                        position: absolute;
                        top: 50%;
                        left: 50%;
                        transform: translate(-50%, -50%);
                    }
                }
            }
        }
    }
}

.dropdown_btn {
    margin-right: 10px;
}
</style>
